'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 进入战斗(掠夺)
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../../consts/code');
var battleRecordModel = require('../../../../models/battleRecordModel');
var atkData = require('../../../../libs/war/atkData');
var battleData = require('../../../../libs/war/battleData');
var onlineService = require('../../../../services/onlineService');
var taskService = require('../../../../services/taskService');
var battleService = require('../../../../services/battleService');
var PlayerManager = require('../../../../libs/playerManager');
var dataApi = require('../../../../libs/dataApi');
var rivalService = require('../../../../services/rivalService');
var activityService = require('../../../../services/activityService.js');
var actType = require('../../../../consts/activityType.js');

// 掠夺
var BATTLE_HARRY = 1;
// 复仇
var BATTLE_REVENGE = 2;

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var road_id = msg.road_id;
    var rival_role_id = msg.rival_role_id; // 黑名单对手角色ID
    if (!road_id && !rival_role_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var role_model;
    var battle_model;
    var battle_record_model;
    var pvp_model;
    var atk_data;
    var def_data;
    var def_role_id = 0;

    var atk_player_manager = new PlayerManager(role_id);
    var def_player_manager;
    var road_player;
    var battle_type = BATTLE_HARRY;
    if (rival_role_id > 0) {
        // 黑名单对手ID大于0，则为黑名单复仇战斗
        battle_type = BATTLE_REVENGE;
    }
    async.waterfall(
        [
            function (cb) {
                atk_player_manager.refreshData(cb);
            },
            function (cb) {
                atk_player_manager.getModel(
                    ['role', 'pvp', 'battle', 'task', 'achieve', 'daily_task', 'accrued'],
                    cb
                );
            },
            function (cb) {
                role_model = atk_player_manager.role;
                battle_model = atk_player_manager.battle;
                pvp_model = atk_player_manager.pvp;

                if (battle_type == BATTLE_REVENGE) {
                    // 黑名单
                    if (!pvp_model.findBlack(rival_role_id)) {
                        return next(null, {
                            code: Code.BATTLE_RIVAL_NOT_IN_BLACK
                        });
                    }

                    def_role_id = rival_role_id;
                } else {
                    road_player = pvp_model.getRoadPlayer(road_id);
                    if (!road_player) {
                        return next(null, {
                            code: Code.BATTLE_RIVAL_NOT_EXIST
                        });
                    }
                    def_role_id = road_player.role_id;
                }

                def_player_manager = new PlayerManager(def_role_id);
                cb();
            },
            function (cb) {
                def_player_manager.refreshData(cb);
            },
            function (cb) {
                def_player_manager.getModel(['role', 'accrued'], cb);
            },
            function (cb) {
                // // 判断被攻击的玩家是否在保护中
                // if (!!def_player_manager.role.isProtect()) {
                //     return next(null, {
                //         code: Code.BATTLE_RIVAL_IN_PROTECT
                //     });
                // }

                // 解除进攻方保护状态
                atk_player_manager.role.removeProtect();

                //     onlineService.checkRoleOnline(road_player.role_id, cb);
                // },
                // function (is_online, cb) {
                //     if (!!is_online) {
                //         return next(null, {
                //             code: Code.BATTLE_USER_IS_ONLINE
                //         });
                //     }

                // 被攻击方数据
                _getDef(def_role_id, cb);
            },
            function (data, cb) {
                def_data = data;

                if (!def_data) {
                    return next(null, {
                        code: Code.BATTLE_DEF_NOT_EXIST
                    });
                }

                // 我方数据
                _getAtk(role_id, cb);
            },
            function (data, cb) {
                atk_data = data;

                if (pvp_model.rival_id !== def_player_manager.getRoleId()) {
                    console.warn('*** rival_id changed ***');
                    console.warn('old_rival_id:', pvp_model.rival_id);
                    console.warn('new_rival_id:', def_player_manager.getRoleId());
                    rivalService.getInfo(def_player_manager, function (err, rival_info) {
                        pvp_model.rival_gold = rival_info.gold;
                        pvp_model.rival_food = rival_info.food;
                        cb();
                    });
                } else {
                    cb();
                }
            },
            function (cb) {
                // 设置成查看到的资源数值
                def_data.total_gold = pvp_model.rival_gold;
                def_data.total_food = pvp_model.rival_food;

                // 存储战斗记录
                battleRecordModel.addRecord(
                    role_id,
                    def_role_id,
                    atk_data,
                    def_data,
                    battle_type,
                    cb);
            },
            function (model, cb) {
                battle_record_model = model;

                // 处理进入掠夺
                battleService.enterBattle(atk_player_manager);

                cb();
            },
            function (cb) {
                // 增加副本掠夺统计
                taskService.addBattleInNum(atk_player_manager);

                // 开服7天掠夺推送
                activityService.push(role_id, actType.BATTLE_NUM, atk_player_manager);
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            atk_player_manager.save();
            return next(null, {
                code: Code.OK,
                result: {
                    record_id: battle_record_model.getRecordId(),
                    atk: atk_data,
                    def: def_data
                }
            });
        }
    );
};

/**
 * 获取攻击方数据
 * @return {[type]} [description]
 */
var _getAtk = function (role_id, cb) {
    atkData.getData(role_id, cb);
};

/**
 * 获取防守方数据
 * @return {[type]} [description]
 */
var _getDef = function (role_id, cb) {
    battleData.getData(role_id, cb);
};
